package org.rambadger.command.listeners;

import org.axonframework.eventhandling.annotation.EventHandler;
import org.axonframework.eventhandling.replay.ReplayAware;
import org.mongojack.DBUpdate;
import org.mongojack.JacksonDBCollection;
import org.rambadger.command.event.*;
import org.rambadger.command.representation.Track;

import static org.rambadger.command.representation.Track.TrackId;

public class TrackListener implements ReplayAware {
    JacksonDBCollection<Track, TrackId> tracks;


    public TrackListener(JacksonDBCollection<Track, TrackId> tracks) {
        this.tracks = tracks;
    }

    @Override
    public void beforeReplay() {
        tracks.drop();
    }

    @Override
    public void afterReplay() {}

    @EventHandler void on(TrackCreated event) {
        tracks.insert(new Track(event.getPlatformId(), event.getTrackId(), event.getTrackName(), event.getDescription()));
    }

    @EventHandler void on(AssignmentAddedToTrack event) {
        Track track = tracks.findOneById(new TrackId(event.getPlatformId(), event.getTrackId()));
        track.addAssignment(event.getIndex(), event.getAssignmentId());
        tracks.save(track);
    }

    @EventHandler void on(AssignmentMovedWithinTrack event){
        Track track = tracks.findOneById(new TrackId(event.getPlatformId(), event.getTrackId()));
        track.moveAssignment(event.getAssignmentId(),event.getIndex());
    }

    @EventHandler void on(AssignmentRemovedFromTrack event){
        Track track = tracks.findOneById(new TrackId(event.getPlatformId(), event.getTrackId()));
        track.removeAssignment(event.getAssignmentId());
        tracks.save(track);
    }
}
